from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
import datetime

from bs4 import BeautifulSoup, Tag
from page.unique_slugify import unique_slugify
from keelback.urls import urlpatterns

class Page(models.Model):
    title = models.CharField(max_length=255, blank=True)
    slug_title = models.SlugField(null=True, unique=True)
    content = models.TextField(blank=True)
    url = models.CharField(max_length=255, blank=True,  null=True,)
    
    creator = models.ForeignKey(User,related_name='+', null=True,
        db_column='creator', blank=True)
    changer = models.ForeignKey(User, null=True, db_column='changer',
        blank=True)
    
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    
    child = models.OneToOneField('self', blank=True, null=True, unique=True,
        related_name='parent')
    sibling = models.OneToOneField('self', blank=True, null=True, unique=True,
        related_name='left_sibling')
    
    trash = models.BooleanField();
    
    #saves and updates created and modified
    def save(self, *args, **kwargs):
        if not self.id:
            self.created = datetime.datetime.today()
        self.modified = datetime.datetime.today()
        
        self.url = None
        
        unique_slugify(self, self.title)
        
        super(Page, self).save(*args, **kwargs)
    
    #save without updating the modified field  
    def save_unmodified(self, *args, **kwargs):
        
        self.url = None
        unique_slugify(self, self.title)
        super(Page, self).save(*args, **kwargs)
        
    #save without updating any extra fields
    def save_clean(self, *args, **kwargs):
        super(Page, self).save(*args, **kwargs)
    
    def get_absolute_url(self):
        #url = cache.get('page_url_'+str(self.id))
        
        if self.url is not None:
            return self.url
        else:
            def url_generator(page):
                if page is not None:
                    return url_generator(find_parent(page))+page.slug_title+"/"
                else:
                    return ""
                
            def find_parent(page):
                try:
                    page.parent
                    return page.parent
                except Page.DoesNotExist:
                    try:
                        return find_parent(page.left_sibling)
                    except Page.DoesNotExist:
                        return None
            
            self.url = reverse('page.views.page')+url_generator(self)
            
            self.save_clean()
            return self.url

    def clear_url_cache(self):
        self.url = None
        self.save_unmodified()
    
    # TODO: Fix this so that it works more dynamically
    # For now it is hardcoded with subclass
    def type(self):
        try:
            type = self.test.type()

        except Page.DoesNotExist:
             type = self.__class__
        
        return type
        
    def get_content(self):
        soup = BeautifulSoup(self.content)
        for link in soup.findAll("link"):
            try:
                page_link = Page.objects.get(id=link['page'])
                tag_soup = BeautifulSoup("<a href='"+page_link.get_absolute_url()+"'>"+link['text']+"</a>")
                tag = tag_soup.a
                link.replaceWith(tag)
            except Page.DoesNotExist:
                pass    
            
        return soup.prettify()    
     
    def __unicode__ (self):
        return self.content
       
    class Meta:
        db_table = u'pages'

class TreeRoot(models.Model):
    page = models.ForeignKey(Page, null=True)

    class Meta:
        db_table = u'tree_root'
        
class Tracked(models.Model):
    page = models.ForeignKey(Page, blank=False, null=False, unique=True)

    class Meta:
        db_table = u'Tracked'

